﻿using System.IO;
using System.Text;
using System.Net;
using System.Xml;

using ECCIT;

namespace ECCIT.Net.SAML2.Protocols
{
    public class StatusCode
    {
        // Fields
        private string code;
        private StatusCode subordinateStatusCode;

        // Properties
        public string Code
        {
            get
            {
                return this.code;
            }
            set
            {
                this.code = value;
            }
        }

        public StatusCode SubordinateStatusCode
        {
            get
            {
                return this.subordinateStatusCode;
            }
            set
            {
                this.subordinateStatusCode = value;
            }
        }

        // Methods
        public StatusCode()
        {
        }

        public StatusCode(string code)
        {
            this.code = code;
        }

        public StatusCode(XmlElement xmlElement)
        {
            if (!IsValid(xmlElement))
            {
                throw new SerializationException("The XML is not a StatusCode.");
            }
            if (xmlElement.HasAttribute("Value"))
            {
                this.code = xmlElement.GetAttribute("Value").Trim();
            }
            foreach (XmlNode node in xmlElement.ChildNodes)
            {
                if (node is XmlElement)
                {
                    XmlElement element = (XmlElement)node;
                    if (IsValid(element))
                    {
                        this.subordinateStatusCode = new StatusCode(element);
                    }
                }
            }
        }

        public static bool IsValid(XmlElement xmlElement)
        {
            return (xmlElement.LocalName.Equals("StatusCode") && xmlElement.NamespaceURI.Equals("urn:oasis:names:tc:SAML:2.0:protocol"));
        }

        public override string ToString()
        {
            return this.code;
        }

        public XmlElement ToXml(XmlDocument xmlDocument)
        {
            XmlElement element = xmlDocument.CreateElement("samlp", "StatusCode", "urn:oasis:names:tc:SAML:2.0:protocol");
            if (!string.IsNullOrEmpty(this.code))
            {
                element.SetAttribute("Value", this.code);
            }
            if (this.subordinateStatusCode != null)
            {
                element.AppendChild(this.subordinateStatusCode.ToXml(xmlDocument));
            }
            return element;
        }
    }
}
